package com.chen.positioning.user.controller;

import com.chen.positioning.feedback.entity.FeedBack;
import com.chen.positioning.user.entity.UserManagement;
import com.chen.positioning.user.service.UserManagementService;
import com.chen.positioning.util.Base64Util;
import com.chen.positioning.util.CommonJsonReturnMessage;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * 用户信息 Controller
 *
 * @author halo
 * @create 2019-07-20 17:09
 */
@Controller
@RequestMapping("/userManagement")
public class UserManagementController {
    @Autowired
    private UserManagementService userManagementService;
    @Autowired
    CommonJsonReturnMessage commonJsonReturnMessage;
    @Autowired
    Base64Util base64Util;

    private static final Logger logger = LoggerFactory.getLogger(UserManagementController.class);

    /**
     * 登录初始页面
     *
     * @return
     */
    //@ResponseBody
    @RequestMapping(value = "/loginIndex", method = {RequestMethod.POST, RequestMethod.GET})
    public String loginIndex() {
        logger.info("已进入登录初始页面....");
        return "login";
    }

    /**
     * 注册初始页面
     *
     * @return
     */
    @RequestMapping(value = "/registerIndex", method = {RequestMethod.POST, RequestMethod.GET})
    public String registerIndex() {
        logger.info("已进入注册初始页面....");
        return "register";
    }

    /**
     * 验证用户名是否存在
     *
     * @param userName
     * @return
     */
    @RequestMapping(value = "/checkUserName", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public boolean checkUserName(String userName) {
        boolean falg = true;//用户名存在
        try {
            logger.info("checkUserName,userName===" + userName);
            int count = userManagementService.checkUserName(userName);
            logger.info("checkUserName,count===" + count);
            if (count < 1) {
                falg = false;//用户名不存在
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("checkUserName error:" + e);
        } finally {
            return falg;
        }

    }

    /**
     * 注册
     * @return
     */
    @RequestMapping(value = "/registerUser", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String registerUser(@RequestBody JSONObject params) {
        try {
//            @RequestParam String userName, @RequestParam String password,@RequestParam String confirmPassword
            logger.info("params:" + params.toString());
            String userName=params.getString("userName");
            String password=params.getString("password");
            String confirmPassword=params.getString("confirmPassword");
            if (StringUtils.isNotBlank(userName)
                    && StringUtils.isNoneBlank(password)
                    && StringUtils.isNotBlank(confirmPassword)) {
                if (password.equals(confirmPassword)) {
                    if ((userName.length() >= 6 && userName.length() <= 15)
                            && (password.length() >= 6 && password.length() <= 15)
                            && (confirmPassword.length() >= 6 && confirmPassword.length() <= 15)) {
                        int count = userManagementService.addUserMangement(userName, base64Util.encryptionByBase64(password));
                        return commonJsonReturnMessage.successReturn("注册成功", count);
                    } else {
                        return commonJsonReturnMessage.failReturn("字段长度不能少于6或者超过15", "");
                    }
                } else {
                    return commonJsonReturnMessage.failReturn("2次输入的密码不一致", "");
                }
            } else {
                return commonJsonReturnMessage.failReturn("必填字段不能为空", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return commonJsonReturnMessage.failReturn("注册失败", e);
        }
    }

    /**
     * 用户登录
     *
     * @param session
     * @param userName
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userLogin", method = {RequestMethod.POST, RequestMethod.GET})
    public String userLogin(HttpServletRequest request,
                            HttpSession session, String userName,
                            String password) {
        try {
            logger.info("userName:" + userName + "password:" + password);
            UserManagement userManagement = new UserManagement();
            if (StringUtils.isNotBlank(userName)
                    && StringUtils.isNoneBlank(password)) {
                if ((userName.length() >= 6 && userName.length() <= 15)
                        && (password.length() >= 6 && password.length() <= 15)) {
                    userManagement = userManagementService.userLogin(userName, base64Util.encryptionByBase64(password));
                    if (null != userManagement && !"".equals(userManagement.getUserName())) {
                        logger.info("userLogin,登录后装入session的值为 userManagement:" + userManagement);
                        session.setAttribute("userManagement", userManagement);
                        return commonJsonReturnMessage.successReturn("登录成功", userManagement);
                    } else {
                        return commonJsonReturnMessage.failReturn("登录失败,用户名或者密码不正确", userManagement);
                    }
                } else {
                    return commonJsonReturnMessage.failReturn("字段长度不能少于6或者超过15", "");
                }
            } else {
                return commonJsonReturnMessage.failReturn("必填字段不能为空", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return commonJsonReturnMessage.failReturn("登录失败", e);
        }
    }

    /**
     * 主页初始页面
     *
     * @return
     */
    @RequestMapping(value = "/mainIndex", method = {RequestMethod.POST, RequestMethod.GET})
    public String mainIndex() {
        logger.info("主页初始页面....");
        return "main";
    }


    /**
     * 设置初始页面
     *
     * @return
     */
    @RequestMapping(value = "/settingIndex", method = {RequestMethod.POST, RequestMethod.GET})
    public String settingIndex(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        logger.info("进入设置初始页面....");
        try {
            ModelAndView modelAndView=new ModelAndView();
            UserManagement userManagement = (UserManagement) session.getAttribute("userManagement");
            if (null != userManagement && userManagement.getUserId() > 0) {
                return "/setting";
            } else {
                response.setContentType("text/html; charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.write("<script>alert('登录超时。。。。');</script>");
                writer.write("<script>window.close();</script>");
                writer.close();
                writer.flush();
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设置初始页面异常:"+e);
            return "";
        }
    }

    /**
     * 注销登录
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/userLogout", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String userLogout(HttpServletRequest request, HttpSession session) {
        try {
            logger.info("注销登录.....");
            UserManagement userManagement = (UserManagement) session.getAttribute("userManagement");
            if (null != userManagement && 0 != userManagement.getUserId()) {
                session.invalidate();//关闭session
                return commonJsonReturnMessage.successReturn("注销成功", "注销成功");

            } else {
                return commonJsonReturnMessage.failReturn("登录超时", "登录超时");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return commonJsonReturnMessage.failReturn("注销失败", e);
        }
    }

    /**
     * 意见反馈初始页
     * @return
     */
    @RequestMapping(value = "/gofeedback", method = {RequestMethod.POST, RequestMethod.GET})
    public String gofeedback() {
        logger.info("进入意见反馈初始页....");
        return "/feedback";
    }

    /**
     * 使用协议
     * @return
     */
    @RequestMapping(value = "/goUseAgreement", method = {RequestMethod.POST, RequestMethod.GET})
    public String goUseAgreement() {
        logger.info("进入使用协议初始页....");
        return "/useAgreement";
    }

    /**
     * 保存意见反馈
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/addFeedback", method = {RequestMethod.POST})
    @ResponseBody
    public String addFeedback(HttpServletRequest request,
                            HttpSession session, String mypositioningPhoneNumber,
                              String feedbackInfo) {
        try {
            logger.info("mypositioningPhoneNumber:" + mypositioningPhoneNumber + "feedbackInfo:" + feedbackInfo);
            UserManagement userManagement= (UserManagement) session.getAttribute("userManagement");
            FeedBack feedBack=new FeedBack();

            if(null!=userManagement && userManagement.getUserId()>0){
                if (StringUtils.isNoneBlank(mypositioningPhoneNumber)
                        && StringUtils.isNoneBlank(feedbackInfo)) {
                    if (mypositioningPhoneNumber.length()<=11 && feedbackInfo.length() <=300) {
                        feedBack.setUserId(userManagement.getUserId());
                        feedBack.setUserTel(mypositioningPhoneNumber);
                        feedBack.setFeedBackContent(feedbackInfo);
                        int count=userManagementService.addFeedback(feedBack);
                        return commonJsonReturnMessage.successReturn("意见提交成功",count);
                    } else {
                        return commonJsonReturnMessage.failReturn("字段长度过长", "");
                    }
                } else {
                    return commonJsonReturnMessage.failReturn("必填字段不能为空", "");
                }
            }else {
                return commonJsonReturnMessage.failReturn("登录超时请重新登录", "");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return commonJsonReturnMessage.failReturn("登录失败", e);
        }
    }
}
